﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GatewayInspect.Common;
using System.Configuration;
using System.Data.Common;
using System.Data.OracleClient;
using GatewayInspect.Model;
using System.Threading;

namespace GatewayInspect.Modules
{
    public partial class InOutGateModule : BaseModule
    {
        private int i_Ant_In = 1, i_Ant_Out = 2;//1号天线对应进闸方向，2号天线对应出闸方向

        private int in_out_state = 1;

        private string strCurRFID_in, strCurTruckNo_in, strCurRFID_out, strCurTruckNo_out;

        string in_park_date;

        string out_park_date;

        string in_depot_date;

        string out_depot_date;

        private RFIDReader_747 reader = null;

        public InOutGateModule()
        {
            InitializeComponent();
        }

        protected override void OnInitialize()
        {
            base.OnInitialize();
            foreach (ToolStripItem item in this.tsMain.Items)
            {
                if (item != tsBtnClose)
                {
                    item.Visible = false;
                }
            }
        }

        protected override void OnInit()
        {
            base.OnInit();

            InitAntNum();//初始化进出闸天线号

            reader = RFIDReader_747.GetInstance();
            reader.InAnt = i_Ant_In;
            reader.OutAnt = i_Ant_Out;
            reader.OnChangeCtrlEnable += new RFIDReader_747.ChangeCtrlEnableHandle(reader_OnChangeCtrlEnable);
            reader.OnShowMsg += new RFIDReader_747.ShowMsgHandler(reader_OnShowMsg);
            reader.IfCloseZhaji += new RFIDReader_747.IfCloseHandler(reader_OnCloseMsg);
            string sOrgType = ConfigurationManager.AppSettings["OrgType"];
            if ("0".Equals(sOrgType))
            {
                reader.OnAfterReadCardInfo += new RFIDReader_747.AfterReadCardInfoHandler(reader_OnAfterReadCardInfo);
            }
            else
            {
                reader.OnAfterReadCardInfo += new RFIDReader_747.AfterReadCardInfoHandler(reader_OnAfterReadCardInfoToDepot);
            }
            reader.OnAfterUpBarrier += new RFIDReader_747.AfterUpBarrierHandler(reader_OnAfterUpBarrier);
        }

        /// <summary>
        /// 初始化进出闸天线号
        /// </summary>
        private void  InitAntNum()
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string strAntNum = config.AppSettings.Settings["InAnt"].Value;
            try
            {
                i_Ant_In = Convert.ToInt32(strAntNum);
            }
            catch
            {
                i_Ant_In = 2;
                MessageBox.Show("进闸方向读卡器天线号设置错误！");
            }
            strAntNum = config.AppSettings.Settings["OutAnt"].Value;
            try
            {
                i_Ant_Out = Convert.ToInt32(strAntNum);
            }
            catch
            {
                i_Ant_Out = 1;
                MessageBox.Show("出闸方向读卡器天线号设置错误！");
            }
        }

        protected override void OnModuleDestroyed()
        {
            base.OnModuleDestroyed();

            if (reader != null)
            {
                reader.OnChangeCtrlEnable -= new RFIDReader_747.ChangeCtrlEnableHandle(reader_OnChangeCtrlEnable);
                reader.OnShowMsg -= new RFIDReader_747.ShowMsgHandler(reader_OnShowMsg);
                string sOrgType = ConfigurationManager.AppSettings["OrgType"];
                if ("0".Equals(sOrgType))
                {
                    reader.OnAfterReadCardInfo -= new RFIDReader_747.AfterReadCardInfoHandler(reader_OnAfterReadCardInfo);
                }
                else
                {
                    reader.OnAfterReadCardInfo -= new RFIDReader_747.AfterReadCardInfoHandler(reader_OnAfterReadCardInfoToDepot);
                }
                
                reader.OnAfterUpBarrier -= new RFIDReader_747.AfterUpBarrierHandler(reader_OnAfterUpBarrier);

                if (reader.IsConnect)
                {
                    reader.EndRead();
                    reader.Disconnect();
                }
            }
        }

        #region 改变界面按钮状态
        private delegate void changeCtrlEnableHandle(string state);

        private void reader_OnChangeCtrlEnable(string state)
        {
            if (this.InvokeRequired)
            {
                changeCtrlEnableHandle h = new changeCtrlEnableHandle(changeCtrlEnableMethod);
                this.BeginInvoke(h, state);
            }
            else
                changeCtrlEnableMethod(state);
        }

        private void changeCtrlEnableMethod(string state)
        {
            switch (state)
            {
                case "conn":
                    btnConnect.Enabled = false;
                    btnDiscon.Enabled = true;
                    btnBegin.Enabled = true;
                    btnStop.Enabled = false;
                    break;
                case "disconn":
                    btnConnect.Enabled = true;
                    btnDiscon.Enabled = false;
                    btnBegin.Enabled = false;
                    btnStop.Enabled = false;
                    break;
                case "scan":
                    btnConnect.Enabled = false;
                    btnDiscon.Enabled = true;
                    btnBegin.Enabled = false;
                    btnStop.Enabled = true;
                    break;
            }
        }
        #endregion

        #region 状态栏显示信息
        private delegate void showMsgHandle(string str);

        private void reader_OnShowMsg(string str)
        {
            if (this.InvokeRequired)
            {
                showMsgHandle h = new showMsgHandle(showMsgMethod);
                this.BeginInvoke(h, str);
            }
            else
            {
                showMsgMethod(str);
            }
        }

        private void showMsgMethod(string str)
        {
            this.lblMsg.Text = str;
        }
        #endregion

        #region 闸机是否闭合
        private delegate void showCloseHandle(string state);

        private void reader_OnCloseMsg(string state)
        {
            if (this.InvokeRequired)
            {
                showCloseHandle h = new showCloseHandle(showCloseMethod);
                this.BeginInvoke(h, state);
            }
            else
            {
                showCloseMethod(state);
            }
        }

        private void showCloseMethod(string state)
        {
            if (state == "0")
            {
                checkBox1.Checked = false;
            }
            else 
            {
                checkBox1.Checked = true; 
            }
            
        }
        #endregion

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (reader != null)
            {
                try
                {
                    reader.Connect();
                    if (reader.IsConnect)
                    {
                        MessageBox.Show("读卡器连接成功！", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(InOutGateModule), ex);
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btnDiscon_Click(object sender, EventArgs e)
        {
            if (reader != null)
            {
                try
                {
                    reader.Disconnect();
                    if (!reader.IsConnect)
                    {
                        MessageBox.Show("断开读卡器成功！", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(InOutGateModule), ex);
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btnBegin_Click(object sender, EventArgs e)
        {
            if (reader != null)
            {
                reader.BeginRead();
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (reader != null)
            {
                reader.EndRead();
            }
        }

        private void reader_OnAfterUpBarrier()
        {
            strCurRFID_in = "";
            strCurTruckNo_in = "";
            strCurRFID_out = "";
            strCurTruckNo_out = "";
        }


       

       

        /// <summary>
        /// 回写汽车市提信息表
        /// </summary>
        /// <param name="chehao"></param>
        private void UpdateOilBill(string chehao, bool bIsIn)
        {
            string strSQL = @"select id from (select id, row_number() over(partition by head_car_no order by print_time desc) rn from wlw_dbc_oil_bill where head_car_no=:chehao and coalesce(if_del,'0')='0') where rn=1";
            DataTable dt = DataAccess.ExecuteDataTable(strSQL, new OracleParameter("chehao", chehao));
            if (dt != null && dt.Rows.Count > 0)
            {
                StringBuilder sbSQL = new StringBuilder();
                sbSQL.Append("update wlw_dbc_oil_bill set ");
                if (Session.CurrentOrgType == (int)OrgType.KQ)//库区
                {
                    if (bIsIn)
                        sbSQL.Append("IN_DEPOT_TIME=sysdate,");
                    else
                        sbSQL.Append("OUT_DEPOT_TIME=sysdate,");
                }
                else if (Session.CurrentOrgType == (int)OrgType.TCC)//停车场
                {
                    if (bIsIn)
                        sbSQL.Append("in_park_time=sysdate,");
                    else
                        sbSQL.Append("out_park_time=sysdate,");
                }
                sbSQL.Append("if_backto_platform='0' where id='" + dt.Rows[0]["ID"].ToString() + "'");
                DataAccess.ExecuteNonQuery(sbSQL.ToString());
            }
        }

        private bool CheckBlackList(string strCarNo, out string strReason)
        {
            strReason = "";
            string strSQL = "select ID,REASON from T_TRUCK_BLACKLIST where ISDEL = '0' and TRUCKNO = '" + strCarNo + "'";
            DataTable dtBlackList = DataAccess.ExecuteDataTable(strSQL);
            if (dtBlackList != null && dtBlackList.Rows.Count > 0)
            {
                strReason = dtBlackList.Rows[0]["REASON"].ToString().Trim();
                return true;
            }
            return false;
        }

        //根据卡号获取车号
        private string GetCarNo(string cardID)
        {
            string strCarNo = string.Empty;
            string strSQL = "select CHEHAO from RFID_READ where CARDID='" + cardID + "' and CARDSTATE='0'";
            DataTable dtRFID = DataAccess.ExecuteDataTable(strSQL);
            if (dtRFID != null && dtRFID.Rows.Count > 0)
            {
                strCarNo = dtRFID.Rows[0]["CHEHAO"].ToString().Trim();
            }
            return strCarNo;
        }
        //读卡后进出停车场的操作
        private void reader_OnAfterReadCardInfo(string strTid, string strEPC, int iAnt)
        {
            try
            {
                if ((iAnt == i_Ant_In) && (!string.IsNullOrWhiteSpace(strCurTruckNo_in) || (strTid == strCurRFID_in)))
                    return;
                if ((iAnt == i_Ant_Out) && (!string.IsNullOrWhiteSpace(strCurTruckNo_out) || (strTid == strCurRFID_out)))
                    return;
                in_out_state = iAnt;
                SetInOutState(iAnt);
                SetTextValue(txtTime, DateTime.Now.ToString());
                AddList("读卡时间：" + DateTime.Now.ToString());
                AddList("天线：" + iAnt);
                AddList("卡号：" + strTid);

                string strCarNo = GetCarNo(strTid);
                string carId = GetCarId(strCarNo);
                if (!string.IsNullOrEmpty(strCarNo))
                {
                    AddList("车号：" + strCarNo);
                    SetTextValue(txtCurrentTruck, strCarNo);
                    //判断黑名单
                    string strReason = "";
                    if (CheckBlackList(strCarNo, out strReason))
                    {
                        AddList("已加入黑名单！");
                        AddList("    ");
                        SetTextValue(txtInfo, "该车已加入黑名单！");
                        AppendTextValue(txtInfo, "\r\n\r\n原因：");
                        AppendTextValue(txtInfo, strReason);
                        return;
                    }
                    if (iAnt == i_Ant_In)
                    {
                        //获取全局进闸时间
                        string timeStr = "select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') AS TIME from dual";
                        DataTable dtTime = DataAccess.ExecuteDataTable(timeStr);
                        if (dtTime != null && dtTime.Rows.Count > 0)
                        {
                            in_park_date = dtTime.Rows[0]["TIME"].ToString();
                        }
                        InsertInGateData(strCarNo, strTid);//插入进闸记录
                        //更新车进入停车场时间（lv）
                        updateInParkTime(strCarNo);

                        strCurRFID_in = strTid;
                        strCurTruckNo_in = strCarNo;
                    }
                    else if (iAnt == i_Ant_Out)
                    {
                        //获取全局出闸时间
                        string timeStr = "select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') AS TIME from dual";
                        DataTable dtTime = DataAccess.ExecuteDataTable(timeStr);
                        if (dtTime != null && dtTime.Rows.Count > 0)
                        {
                            out_park_date = dtTime.Rows[0]["TIME"].ToString();
                        }
                        UpdateOutGateData(strCarNo, strTid);
                        //更新出停车场时间（lv）
                        string result = updateOutParkTime(carId, strCarNo);
                        AddList(result);
                        SetTextValue(txtInfo, result);
                        strCurRFID_out = strTid;
                        strCurTruckNo_out = strCarNo;
                      
                    }
                    AddList("起杆放行...");
                    SetTextValue(txtInfo, "起杆放行...");
                    reader.UpBarrier();//起杆放行
                    
                }
                else//未关联车号
                {
                    AddList("未关联车号...");
                    SetTextValue(txtCurrentTruck, "");
                    SetTextValue(txtInfo, "未关联车号...");
                }
                AddList("    ");
            }
            catch (Exception ex)
            {
                AddList(ex.Message);
                AddList("    ");
                LogHelper.WriteLog(typeof(InOutGateModule), ex);
            }
        }
        //判断该车是否在派车指令表中
        private bool isInPczl(string carNo) {
            //派车指令中是否有这个车
            string strSql = "select * from TRUCK_IN_ORDER_TNO t where t.IF_END='0' and t.TRUCK_NO='" + carNo + "'";
            DataTable jl = DataAccess.ExecuteDataTable(strSql);
            if (jl != null && jl.Rows.Count > 0)
            {
                return true;
            }
            else {
                return false;
            }
        }
        //根据车牌号获取车id（lv）
        private string GetCarId(string cardNo)
        {
            string strCarId = string.Empty;
            string strSQL = "select ID from WLW_DBC_OILCAR_INFO where CAR_NO='" + cardNo + "'";
            DataTable dtRFID = DataAccess.ExecuteDataTable(strSQL);
            if (dtRFID != null && dtRFID.Rows.Count > 0)
            {
                strCarId = dtRFID.Rows[0]["ID"].ToString().Trim();
            }
            return strCarId;
        }
        //根据车id判断车是否有订单记录，根据结果更新进停车场时间（lv）
        private void updateInParkTime(string cardNo)
        {
            string strCarId = string.Empty;
            string strSQL = "Select * From (Select id  as ID , if_import as IF_IMPORT  From VI_DBC_OIL_BILL Where HEAD_CAR_NO = '" + cardNo + "'  And nvl(IF_END, '0' ) = '0' and (depot_code!='02' or depot_code!='03') Order By PRINT_TIME Desc) Where ROWNUM = 1 ";
            DataTable dtRFID = DataAccess.ExecuteDataTable(strSQL);
            if (dtRFID != null && dtRFID.Rows.Count > 0)
            {
                string bill_id = dtRFID.Rows[0]["ID"].ToString().Trim();
                string if_import = dtRFID.Rows[0]["IF_IMPORT"].ToString().Trim();
                if (if_import=="0")
                {
                    try {
                        strSQL = "update WLW_DBC_OIL_BILL set in_park_time=to_date('" + in_park_date + "','yyyy-mm-dd hh24:mi:ss') ,PARK_NAME='" + Session.CurrentOrgName + "', PARK_CODE = '" + Session.CurrentOrgCode + "' , out_park_time=null where ID='" + bill_id + "' ";
                        DataAccess.ExecuteNonQuery(strSQL);
                    }catch(Exception e){
                        LogHelper.WriteLog(typeof(InOutGateModule), cardNo + "进停车场更新物流网失败");
                    }
                    

                }
                
            }

        }
        //根据车id判断车是否有订单记录，根据结果更新出停车场时间（lv）
        private string updateOutParkTime(string carId, string carNo)
        {
            string result = "";
            string strCarId = string.Empty;
            //检查平台该车是否有已接单、未完成的正常订单记录
            string ddSQL = "Select * From (Select ID,IF_IMPORT,to_char(IMPORT_TIME,'yyyy-mm-dd hh24:mi:ss')IMPORT_TIME,PLAN_NO,HEAD_CAR_NO  From VI_DBC_OIL_BILL Where HEAD_CAR_NO = '" + carNo + "'  And nvl(IF_END, '0' ) = '0' and (depot_code!='02' or depot_code!='03') Order By PRINT_TIME Desc) Where ROWNUM = 1 ";
            DataTable dtDD = DataAccess.ExecuteDataTable(ddSQL);
            if (dtDD != null && dtDD.Rows.Count > 0)
            {
                //result = "该车有未结束订单且已有进场时间，更新物流网出场时间！";
                string bill_id = dtDD.Rows[0]["ID"].ToString();
                string if_import = dtDD.Rows[0]["IF_IMPORT"].ToString();
                string import_time = dtDD.Rows[0]["IMPORT_TIME"].ToString();
                string plan_no = dtDD.Rows[0]["PLAN_NO"].ToString();
                string head_car_no = dtDD.Rows[0]["HEAD_CAR_NO"].ToString();
                if (if_import == "0")
                {

                    try {
                        string fcSQL = "update WLW_DBC_OIL_BILL set out_park_time=to_date('" + out_park_date + "','yyyy-mm-dd hh24:mi:ss') where id='" + bill_id + "' ";
                        DataAccess.ExecuteNonQuery(fcSQL);
                        result = "无放车指令，更新平台出场时间成功！";
                    }catch(Exception e){
                        LogHelper.WriteLog(typeof(InOutGateModule), carNo + "无放车指令，出停车场更新物流网失败");
                    }
                    
                }
                if (if_import == "1")
                {
                    string zlSQL = "select IF_END,to_char(XH) XH,PLAN_NO from  TRUCK_IN_ORDER_TNO where truck_no= '" + carNo + "' and PLAN_NO='" + plan_no + "' and order_time=to_date('" + import_time + "','yyyy-mm-dd hh24:mi:ss')";
                    DataTable dtXh = DataAccess.ExecuteDataTable(zlSQL);
                    if (dtXh != null && dtXh.Rows.Count > 0)
                    {
                        string xh = dtXh.Rows[0]["XH"].ToString();
                        string if_end = dtXh.Rows[0]["IF_END"].ToString();
                        if (if_end == "0")
                        {
                            try {
                                string fcSQL = "update WLW_DBC_OIL_BILL set out_park_time=to_date('" + out_park_date + "','yyyy-mm-dd hh24:mi:ss') where id='" + bill_id + "' ";
                                DataAccess.ExecuteNonQuery(fcSQL);
                                //更新TRUCK_IN_ORDER_TNO这个表
                                string strSQLTruck = "update TRUCK_IN_ORDER_TNO set IF_END='1' where TRUCK_NO='" + carNo + "' "
                                  + "and plan_no ='" + plan_no + "' and xh='" + xh + "'";
                                DataAccess.ExecuteNonQuery(strSQLTruck);
                                result = "有放车指令，更新平台出场时间成功！";
                            }catch(Exception e){
                                LogHelper.WriteLog(typeof(InOutGateModule), carNo + "有放车指令，出停车场更新物流网失败");
                            }
                            
                        }
                        else 
                        {
                            result = "放车指令已执行，不更新时间！";
                        }
                    }
                    else 
                    {
                        result = "未找到符合的放车指令，不更新时间！";
                    }
                }
               
            }
            else 
            {
                result = "该车没有已接且未完成的订单！";
            }
            return result;

        }
        //读卡后进出库区的操作
        private void reader_OnAfterReadCardInfoToDepot(string strTid, string strEPC, int iAnt)
        {
            try
            {
                if ((iAnt == i_Ant_In) && (!string.IsNullOrWhiteSpace(strCurTruckNo_in) || (strTid == strCurRFID_in)))
                    return;
                if ((iAnt == i_Ant_Out) && (!string.IsNullOrWhiteSpace(strCurTruckNo_out) || (strTid == strCurRFID_out)))
                    return;
                in_out_state = iAnt;
                SetInOutState(iAnt);
                SetTextValue(txtTime, DateTime.Now.ToString());
                AddList("读卡时间：" + DateTime.Now.ToString());
                AddList("天线：" + iAnt);
                AddList("卡号：" + strTid);
                string strCarNo = GetCarNo(strTid);
                string carId = GetCarId(strCarNo);
                if (!string.IsNullOrEmpty(strCarNo))
                {
                    AddList("车号：" + strCarNo);
                    SetTextValue(txtCurrentTruck, strCarNo);
                    if (iAnt == i_Ant_In)
                    {
                        //获取全局进闸时间
                        string timeStr = "select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') AS TIME from dual";
                        DataTable dtTime = DataAccess.ExecuteDataTable(timeStr);
                        if (dtTime != null && dtTime.Rows.Count > 0)
                        {
                            in_depot_date = dtTime.Rows[0]["TIME"].ToString();
                            in_park_date = in_depot_date;
                        }
                        //InsertInGateData(strCarNo, strTid);//插入进闸记录,现在代码加入到更新物流网时间代码里了
                        //更新车进入库区时间本地跟物流网都更新（lv）
                        string result = updateInDepotTime(strCarNo,strTid);
                        if (result=="0")
                        {
                            AddList("更新物流网进场时间...");
                            SetTextValue(txtInfo, "更新物流网进场时间...");
                        }
                        else if (result == "1")
                        {
                            AddList("车辆未注册，不抬杆！");
                            SetTextValue(txtInfo, "车辆未注册，不抬杆！");
                            return;
                        }
                        else if (result == "2")
                        {
                            AddList("该车未通过审核，不抬杆！");
                            SetTextValue(txtInfo, "该车未通过审核，不抬杆！");
                            return;
                        }
                        else if (result == "3")
                        {
                            AddList("该车未接单，不抬杆！");
                            SetTextValue(txtInfo, "该车未接单，不抬杆！");
                            return;
                        }
                        else if (result == "4")
                        {
                            AddList("该车未生成放车指令，不抬杆！");
                            SetTextValue(txtInfo, "该车未生成放车指令，不抬杆！");
                            return;
                        }
                        else if (result == "5")
                        {
                            AddList("该车未出停车场，不抬杆！");
                            SetTextValue(txtInfo, "该车未出停车场，不抬杆！");
                            return;
                        }
                        else if (result == "6")
                        {
                            AddList("不在作业时间段内，不抬杆！");
                            SetTextValue(txtInfo, "不在作业时间段内，不抬杆！");
                            return;
                        }
                        else if (result == "7")
                        {
                            AddList("该车在黑名单中，不抬杆！");
                            SetTextValue(txtInfo, "该车在黑名单中，不抬杆！");
                            return;
                        }
                        
                        strCurRFID_in = strTid;
                        strCurTruckNo_in = strCarNo;
                    }else{
                        //获取全局进闸时间
                        string timeStr = "select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') AS TIME from dual";
                        DataTable dtTime = DataAccess.ExecuteDataTable(timeStr);
                        if (dtTime != null && dtTime.Rows.Count > 0)
                        {
                            out_depot_date = dtTime.Rows[0]["TIME"].ToString();
                            out_park_date = out_depot_date;
                        }
                        //更新出闸记录
                        UpdateOutGateData(strCarNo, strTid);
                        //更新出库区时间（lv）
                        updateOutDepotTime(strCarNo);
                        strCurRFID_out = strTid;
                        strCurTruckNo_out = strCarNo;
                    }
                    AddList("起杆放行...");
                    SetTextValue(txtInfo, "起杆放行...");
                    reader.UpBarrier();//起杆放行
                    string type = ConfigurationManager.AppSettings["DeviceType"];
                    if(type=="3"){
                        Thread.Sleep(15000);
                    }
                    
                }
                else//未关联车号
                {
                    AddList("未关联车号...");
                    SetTextValue(txtCurrentTruck, "");
                    SetTextValue(txtInfo, "未关联车号...");
                }
                AddList("      ");
            }
            catch (Exception ex)
            {
                AddList(ex.Message);
                AddList("      ");
                LogHelper.WriteLog(typeof(InOutGateModule), ex);
            }
        }
        //插入进闸记录
        private void  InsertInGateData(string chehao, string cardid)
        {
            //判断该车1小时内是否有进这个停车场的记录
            string strSQLInOneHour = "select CHEHAO from IN_OUT_GATE where ORGCODE='" + Session.CurrentOrgCode + "' and CHEHAO='" + chehao + "' and IN_OUT_BS='1' and (sysdate-in_date)*24*60<60";
            DataTable dtInOneHour = DataAccess.ExecuteDataTable(strSQLInOneHour);
            if (dtInOneHour != null && dtInOneHour.Rows.Count > 0)
            {
               
            }
            else 
            {
               
                string strSQL = "select CHEHAO from IN_OUT_GATE where CHEHAO='" + chehao + "' and IN_OUT_BS='1'";
                DataTable dt = DataAccess.ExecuteDataTable(strSQL);
                if (dt != null && dt.Rows.Count > 0)
                {
                    string strSQL1 = "update IN_OUT_GATE set IN_OUT_BS='2',OUT_DATE=to_date('" + in_park_date + "','yyyy-mm-dd hh24:mi:ss') where CHEHAO='" + chehao + "' and IN_OUT_BS='1'";
                    DataAccess.ExecuteNonQuery(strSQL1);

                    strSQL = "insert into IN_OUT_GATE(CHEHAO,IN_DATE,CARDID,IN_OUT_BS,RECTIME,IN_OPERATOR,ORGCODE) values('" + chehao + "',to_date('" + in_park_date + "','yyyy-mm-dd hh24:mi:ss'),'" + cardid + "','1',to_date('" + in_park_date + "','yyyy-mm-dd hh24:mi:ss'),'" + Session.CurrentUserName + "','" + Session.CurrentOrgCode + "')";
                    DataAccess.ExecuteNonQuery(strSQL);
                }
                else
                {
                    strSQL = "insert into IN_OUT_GATE(CHEHAO,IN_DATE,CARDID,IN_OUT_BS,RECTIME,IN_OPERATOR,ORGCODE) values('" + chehao + "',to_date('" + in_park_date + "','yyyy-mm-dd hh24:mi:ss'),'" + cardid + "','1',to_date('" + in_park_date + "','yyyy-mm-dd hh24:mi:ss'),'" + Session.CurrentUserName + "','" + Session.CurrentOrgCode + "')";
                    DataAccess.ExecuteNonQuery(strSQL);
                    
                }
            }
            
            //UpdateOilBill(chehao, true);
        }
        //更新
        private void UpdateOutGateData(string chehao, string cardid)
        {
                 //判断该车1小时内是否有出这个停车场的记录
            //string strSQLInOneHour = "select CHEHAO from IN_OUT_GATE where ORGCODE='" + Session.CurrentOrgCode + "' and CHEHAO='" + chehao + "' and IN_OUT_BS='2' and (sysdate-out_date)*24*60<60";
            //DataTable dtInOneHour = DataAccess.ExecuteDataTable(strSQLInOneHour);
            //if (dtInOneHour != null && dtInOneHour.Rows.Count > 0)
            //{

            //}
            //else
            //{
                
                string strSQL = "select RECTIME from IN_OUT_GATE where ORGCODE='" + Session.CurrentOrgCode + "' and CHEHAO='" + chehao + "' and IN_OUT_BS='1' order by RECTIME desc ";
                DataTable dtInOutGate = DataAccess.ExecuteDataTable(strSQL);//取最后一条进闸数据
                if (dtInOutGate != null && dtInOutGate.Rows.Count > 0)
                {
                    //string strRecTime = dtInOutGate.Rows[0]["RECTIME"].ToString();
                    string strSQL1 = "UPDATE IN_OUT_GATE SET OUT_DATE=to_date('" + out_park_date + "','yyyy-mm-dd hh24:mi:ss'),IN_OUT_BS='2',OUT_OPERATOR='" + Session.CurrentUserName + "' " +
                        " WHERE  CHEHAO='" + chehao + "' AND IN_OUT_BS='1'";
                    DataAccess.ExecuteNonQuery(strSQL1);
                }
                else//没有进闸数据
                {
                    //判断该车10分钟内是否有出这个停车场的记录
                    string strSQLInOneHour = "select CHEHAO from IN_OUT_GATE where ORGCODE='" + Session.CurrentOrgCode + "' and CHEHAO='" + chehao + "' and IN_OUT_BS='2' and (sysdate-out_date)*24*60<10";
                    DataTable dtInOneHour = DataAccess.ExecuteDataTable(strSQLInOneHour);
                    if (dtInOneHour != null && dtInOneHour.Rows.Count > 0)
                    {

                    }
                    else 
                    {
                        string strSQL2 = "UPDATE IN_OUT_GATE SET OUT_DATE=to_date('" + out_park_date + "','yyyy-mm-dd hh24:mi:ss'),IN_OUT_BS='2',OUT_OPERATOR='" + Session.CurrentUserName + "' " +
                        " WHERE  CHEHAO='" + chehao + "' AND IN_OUT_BS='1'";
                        DataAccess.ExecuteNonQuery(strSQL2);
                        InsertOutGateData(chehao, cardid);
                    }
                    
                }
                
            //}
               
        }
        //插入出闸记录
        private void InsertOutGateData(string chehao, string cardid)
        {
            //string strSQL = "select CHEHAO from IN_OUT_GATE where ORGCODE='" + Session.CurrentOrgCode + "' and CHEHAO='" + chehao + "' and IN_OUT_BS='2'";
            //DataTable dt = DataAccess.ExecuteDataTable(strSQL);
            //if (dt != null && dt.Rows.Count == 0)
            //{
            //    strSQL = "insert into IN_OUT_GATE(CHEHAO,OUT_DATE,CARDID,IN_OUT_BS,RECTIME,OUT_OPERATOR,ORGCODE) values('" + chehao + "',sysdate,'" + cardid + "','2',sysdate,'" + Session.CurrentUserName + "','" + Session.CurrentOrgCode + "')";
            //    DataAccess.ExecuteNonQuery(strSQL);
            //}
            string strSQL = "insert into IN_OUT_GATE(CHEHAO,OUT_DATE,CARDID,IN_OUT_BS,RECTIME,OUT_OPERATOR,ORGCODE) values('" + chehao + "',to_date('" + out_park_date + "','yyyy-mm-dd hh24:mi:ss'),'" + cardid + "','2',to_date('" + out_park_date + "','yyyy-mm-dd hh24:mi:ss'),'" + Session.CurrentUserName + "','" + Session.CurrentOrgCode + "')";
            DataAccess.ExecuteNonQuery(strSQL);
        }
        //根据车id判断车六小时内是否出过停车场（lv）
        private bool ifOutPark(string carNo)
        {
            string strSQL = "Select sysdate - numtodsinterval(6, 'hour') as ldt From dual";
            DataTable dtRFID = DataAccess.ExecuteDataTable(strSQL);

            string ldt = dtRFID.Rows[0]["ldt"].ToString().Trim();
            string strIfHasSQL = "select * from (Select IN_DATE, OUT_DATE From VI_PARK_OUT WHERE CHEHAO = '" + carNo + "'  and OUT_DATE >=to_date('" + ldt + "','yyyy-mm-dd hh24:mi:ss')  ORDER BY OUT_DATE desc) where ROWNUM = 1";
            DataTable dtIfHas = DataAccess.ExecuteDataTable(strIfHasSQL);
            if (dtIfHas != null && dtIfHas.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        //根据车id判断车是否有装车记录（lv）
        private bool ifHasRecord(string carId)
        {
            string strCarId = string.Empty;
            string strSQL = "select * from WLW_DBC_OIL_BILL where HEAD_CAR_ID='" + carId + "' "
            + "and in_depot_time is null and if_print='1' and if_del='0'";
            DataTable dtRFID = DataAccess.ExecuteDataTable(strSQL);
            if (dtRFID != null && dtRFID.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        //根据车id判断车是否有订单记录，根据结果更新进库区时间（lv）
        private string updateInDepotTime(string carNo, string strTid)
        {
            string result = "0";//0表示流程正确
            //1判断是否已注册
            string zcSQL = "select CAR_NO,IF_AUDIT, IF_LOCK from WLW_DBC_OILCAR_INFO  where CAR_NO = '" + carNo + "'";
            DataTable dtZC = DataAccess.ExecuteDataTable(zcSQL);
            if (dtZC != null && dtZC.Rows.Count > 0)
            {
                string if_audit = dtZC.Rows[0]["IF_AUDIT"].ToString();
                string if_lock = dtZC.Rows[0]["IF_LOCK"].ToString();
                //是否已审核通过
                if (if_audit == "1")
                {
                    //是否接单
                    string jdSQL = "Select ID,IF_IMPORT, to_char(OUT_PARK_TIME,'yyyy-mm-dd hh24:mi:ss')OUT_PARK_TIME,PLAN_NO " +
	                                " From vi_dbc_oil_bill "+
                                    " Where head_car_no =  '" + carNo + "'  And nvl(if_end, '0' ) = '0' and depot_code='" + Session.CurrentOrgCode + "'";
                    DataTable dtJD = DataAccess.ExecuteDataTable(jdSQL);
                    if (dtJD != null && dtJD.Rows.Count > 0)
                    {
                        string if_import = dtJD.Rows[0]["IF_IMPORT"].ToString();
                        string out_park_time = dtJD.Rows[0]["OUT_PARK_TIME"].ToString();
                        string plan_no = dtJD.Rows[0]["PLAN_NO"].ToString();
                        string bill_id = dtJD.Rows[0]["ID"].ToString();
                        if (if_import == "1")
                        {
                            if (string.IsNullOrEmpty(out_park_time))
                            {
                                result = "5";//该车未出停车场
                            }
                            else 
                            {
                                 //是否在作业时间段内
                                string zySQL = "select dispatch_begin_time,dispatch_end_time from wlw_DBC_OIL_PLAN  where plan_no= '" + plan_no + "' AND "+
                                                "sysdate >= dispatch_begin_time and sysdate<= dispatch_end_time ";
                                DataTable dtZY = DataAccess.ExecuteDataTable(zySQL);
                                if (dtZY != null && dtZY.Rows.Count > 0)
                                {
                                    if(if_lock=="1")
                                    {
                                        result = "7";
                                    }
                                    else
                                    {
                                        try {
                                            InsertInGateData(carNo, strTid);//插入进闸记录
                                            string strSQL = "update WLW_DBC_OIL_BILL set in_depot_time=to_date('" + in_depot_date + "','yyyy-mm-dd hh24:mi:ss') where id='" + bill_id + "' ";
                                            DataAccess.ExecuteNonQuery(strSQL);
                                            result = "0";//0表示流程正确
                                        }catch(Exception e){
                                            LogHelper.WriteLog(typeof(InOutGateModule), carNo + "进库区更新物流网失败");
                                        }
                                        
                                    }
                                }
                                else 
                                {
                                    result = "6";
                                }
                                
                            }
                        }
                        else 
                        {
                            result = "4";//无放车指令
                        }
                    }
                    else 
                    {
                        result = "3";//该车在库区没有装车业务
                    }

                }
                else 
                {
                    result = "2";//未审核通过
                }
                
            }
            else 
            {
                result = "1";//未注册
            }
            return result;

        }
        //根据车id判断车是否有订单记录，根据结果更出库区时间（lv）
        private void updateOutDepotTime(string carNo)
        {
            string idSQL = "Select * From (Select id  as ID  From VI_DBC_OIL_BILL Where HEAD_CAR_NO = '" + carNo + "'  And nvl(IF_END, '0' ) = '0' And DEPOT_CODE='" + Session.CurrentOrgCode + "' And  in_park_time is not null and out_park_time is not null AND in_depot_time is not null Order By PRINT_TIME Desc) Where ROWNUM = 1 ";
            DataTable dtID = DataAccess.ExecuteDataTable(idSQL);
            if (dtID != null && dtID.Rows.Count > 0)
            {
                try
                {
                    string bill_id = dtID.Rows[0]["ID"].ToString();
                    string strSQL = "update WLW_DBC_OIL_BILL set out_depot_time=to_date('" + out_depot_date + "','yyyy-mm-dd hh24:mi:ss') where id='" + bill_id + "' ";
                    DataAccess.ExecuteNonQuery(strSQL);
                }
                catch (Exception e)
                {
                    LogHelper.WriteLog(typeof(InOutGateModule), carNo + "出库区更新物流网失败");
                }
                


            }

        }

        #region 添加读卡信息显示
        private delegate void AddListHandle(string str);

        private void AddList(string str)
        {
            if (this.InvokeRequired)
            {
                AddListHandle h = new AddListHandle(AddListMethod);
                this.BeginInvoke(h, str);
            }
            else
            {
                AddListMethod(str);
            }
        }

        private void AddListMethod(string str)
        {
            if (listLog.Items.Count >= 5000)
            {
                listLog.Items.Clear();
            }
            listLog.Items.Add(str);
            listLog.TopIndex = listLog.Items.Count - (int)(listLog.Height / listLog.ItemHeight);
        }
        #endregion

        #region 设置进出闸状态显示
        private delegate void SetInOutStateHandle(int state);

        private void SetInOutState(int state)
        {
            if(this.InvokeRequired)
            {
                SetInOutStateHandle h = new SetInOutStateHandle(SetInOutStateMethod);
                this.BeginInvoke(h, state);
            }
            else
            {
                SetInOutStateMethod(state);
            }
        }

        private void SetInOutStateMethod(int state)
        {
            chbIn.Checked = (state == i_Ant_In);
            chbOut.Checked = (state == i_Ant_Out);
        }
        #endregion

        #region 设置TextBox显示
        private delegate void SetTextValueHandle(Control ctrl, string value);

        private void SetTextValue(Control ctrl, string value)
        {
            if (this.InvokeRequired)
            {
                SetTextValueHandle handle = new SetTextValueHandle(SetTextValueMethod);
                this.BeginInvoke(handle, ctrl, value);
            }
            else
                SetTextValueMethod(ctrl, value);
        }

        private void SetTextValueMethod(Control ctrl, string value)
        {
            ctrl.Text = value;
        }

        private delegate void AppendTextValueHandle(TextBox ctrl, string value);

        private void AppendTextValue(TextBox ctrl, string value)
        {
            if (this.InvokeRequired)
            {
                AppendTextValueHandle handle = new AppendTextValueHandle(AppendTextValueMethod);
                this.BeginInvoke(handle, ctrl, value);
            }
            else
                AppendTextValueMethod(ctrl, value);
        }

        private void AppendTextValueMethod(TextBox ctrl, string value)
        {
            ctrl.AppendText(value);
        }
        #endregion

        //private void listLog_DrawItem(object sender, DrawItemEventArgs e)
        //{
        //    string s = this.listLog.Items[e.Index].ToString();
        //    if ((e.State & DrawItemState.Selected) == 0)
        //    {
        //        e.Graphics.FillRectangle(Brushes.White, e.Bounds);
        //        if (in_out_state == i_Ant_In)
        //        {
        //            e.Graphics.DrawString(s, this.Font, Brushes.Green, e.Bounds);
        //        }
        //        else
        //        {
        //            e.Graphics.DrawString(s, this.Font, Brushes.Blue, e.Bounds);
        //        }
        //    }
        //    else
        //    {
        //        e.Graphics.FillRectangle(Brushes.Blue, e.Bounds);
        //        e.Graphics.DrawString(s, this.Font, Brushes.White, e.Bounds);
        //    }
        //}
    }
}
